package cn.com.inossem.utils;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;

import java.io.File;

import cn.com.inossem.activity.NimApplication;

/**
 * 拍照相册工具类
 * Created by Mickey.Li
 * Time 2017-10-19 上午 11:27
 */
public class SystemPictureUtil {
	private final static String CAMERA_FILE_NAME = "cameraTemp.jpg";
	private final static String CLIP_FILE_NAME = "clipTemp.jpg";
	private static Intent mIntent;

	/**
	 * 相册
	 */
	public static void getPictureFromAlbum(Activity activity, int requestCode) {
		mIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		activity.startActivityForResult(mIntent, requestCode);
	}

	/**
	 * 相机
	 */
	public static Uri getPictureFromCamera(Activity activity, int requestCode) {
		Uri localUri = getTempFile(activity, CAMERA_FILE_NAME);
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			mIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			mIntent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
			mIntent.putExtra(MediaStore.EXTRA_OUTPUT, localUri);
			activity.startActivityForResult(mIntent, requestCode);
		} else {
			ToastUtil.show(activity, "没有储存卡");
		}
		return localUri;
	}

	/**
	 * 剪裁
	 */
	public static Uri getPictureFromClip(Activity activity, int requestCode, Uri uri) {
		Uri localUri = getTempFile(activity, CLIP_FILE_NAME);
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// crop为true是设置在开启的intent中设置显示的view可以剪裁
		intent.putExtra("crop", "false");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX,outputY 是剪裁图片的宽高
		intent.putExtra("outputX", 200);
		intent.putExtra("outputY", 200);
		intent.putExtra("return-data", false);
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		intent.putExtra(MediaStore.EXTRA_OUTPUT, localUri);
		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		activity.startActivityForResult(intent, requestCode);
		return localUri;
	}

	private static Uri getTempFile(Activity activity, String picName) {
		File dir = new File(Environment.getExternalStorageDirectory().getPath() + "/SapApp");
		if (!dir.exists()) {
			dir.mkdirs();
		}
		File f = new File(dir, picName);
		if (picName.equals(CLIP_FILE_NAME)) {
			if (NimApplication.MANUFACTURER.equals("samsung") || NimApplication.MANUFACTURER.equals("Xiaomi")) {
				return Uri.fromFile(f);
			}
		}
		if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
			return Uri.fromFile(f);
		} else {
			return FileProvider.getUriForFile(activity, activity.getPackageName() + ".fileprovider", f);
		}
	}
}
